package com.alphathink.BitMapUtil;

import java.io.File;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

/**
 * 
 * @author zyn
 * 
 */
public class DecodeBitmap {

	/**
	 * 从一输入流中解析图片至目标大小
	 * 
	 * @param stream
	 *            输入流
	 * @param name
	 *            文件名称。此名称是本文件唯一标示符。
	 * @param targetWidth
	 *            目标宽度
	 * @param targetHeight
	 *            目标高度
	 * @return 如果无法存储至本地文件则返回null;
	 */
	public static Bitmap decodeBtimapFromStream(InputStream stream,
			String name, int targetWidth, int targetHeight) {
		// ���ش洢ʧ�ܷ���null
		if (!BitmapDiskCache.getInstance().cacheBitmapFromStream(stream, name)) {
			return null;
		}
		return decodeBtimapFromFile(BitmapDiskCache.CACHE_DIR + File.separator
				+ name, targetWidth, targetHeight);
	}

	/**
	 * 将一个图片文件进行解析到目标大小。<br>
	 * <b>注意:</b>本方法不检查文件是否存在或者为图片文件。如果不符要求将会产生异常。
	 * 
	 * @param pathName
	 *            文件路径名称
	 * @param targetWidth
	 *            目标宽度
	 * @param targetHeight
	 *            目标高度
	 * @return 解析结果
	 */
	public static Bitmap decodeBtimapFromFile(String pathName, int targetWidth,
			int targetHeight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);
		options.inSampleSize = caculateSamplesize(options, targetWidth,
				targetHeight);
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(pathName, options);
	}

	/**
	 * 根据bitmap现有的options和目标大小，计算出bitmap的压缩比。<br>
	 * 
	 * @param options
	 *            图片选项
	 * @param targetWidth
	 *            目标宽度
	 * @param targetHeight
	 *            目标高度
	 * @return 计算出的压缩比
	 */
	public static int caculateSamplesize(Options options, int targetWidth,
			int targetHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (height > targetHeight || width > targetWidth) {
			final int halfHeight = height / 2;
			final int halfWidth = width / 2;
			// �����ֻҪ��һ�߲�����Ŀ���С����
			while ((halfHeight / inSampleSize) > targetHeight
					&& (halfWidth / inSampleSize) > targetWidth) {
				inSampleSize *= 2;
			}
		}
		System.out.println("DecodeBitmap-->caculateSamplesize-->inSampleSize="
				+ inSampleSize);
		return inSampleSize;
	}
}
